# applys a certain strategy to a single stock
# uses blotter to handle the portfolio

applyStrategy <- function(groupcode, symbol="", pattern, direction, LL=0, WL=0,
                          Pversion=0, initEq=0, EqPerTrade=5000, TxnFees=0,
                          duration=10, portfoliostring="p", accountstring="a") {
  if (groupcode != "") {
    groupinfo <- getDBGroup(groupcode)  # retrieve table with stock_id, code, from, to
    #portfStartDate <- min(groupinfo[,"from"])
    patternlist <- getCSPGroupPattern(groupcode, Pversion=Pversion)
    patternlistnames <- names(patternlist)
  }
  
  if (symbol!="") {
    # if symbol given, do work only for this single symbol
    groupsymbols = symbol
  } else {
    groupsymbols = groupinfo[,"code"]
  }
  
  resetBlotterEnvironment()
  
  # loop throught every group member (if no dedicated symbol given)
  for (symbol in groupsymbols) {
  
    symstring <- paste(symbol, ".vadb", sep="")
    mySymXTS = patternlist[[symbol]]
  
    fromtodates <- getGroupMember(groupinfo, symbol)
    subsetstring = paste(fromtodates[1], "/", sep="")             # ensure that TS and myOrderXTS have same indexes
    subsetstring1= paste(fromtodates[1], fromtodates[2], sep="/") # cut transactions after test timespan
    OHLC <- get(symstring)[subsetstring]
    flag <- 1
  
    # loop through every pattern
    for (i in 1:length(pattern)) {
      EntryXTS = mySymXTS[,pattern[i]]
  
      if (direction[i]=="long") {
        OrderTS <- merge(!EntryXTS, EntryXTS, 0, 
                     (LL[i]>0) * Cl(get(symstring)) * EntryXTS[,1] * (1-.01*LL[i]),
                     (WL[i]>0) * Cl(get(symstring)) * EntryXTS[,1] * (1+.01*WL[i]))
        colnames(OrderTS) <- c("dummy", "long", "short", "stoploss", "stopwin")
      } else if (direction[i]=="short") {
        OrderTS <- merge(!EntryXTS, EntryXTS, 0,
                     (LL[i]>0) * Cl(get(symstring)) * EntryXTS[,1] * (1+.01*LL[i]), 
                     (WL[i]>0) * Cl(get(symstring)) * EntryXTS[,1] * (1-.01*WL[i]))
        colnames(OrderTS) <- c("dummy", "short", "long", "stoploss", "stopwin")
      }
      # remove dummy column (dummy column is to avoid error if EntryTS contains no single TRUE)
      OrderTS <- OrderTS[,2:5]
      OL <- orderLogic(OHLC, OrderTS, n=duration)
      if (dim(OL)[1] > 0) {      # only if there are trades
        OL <- OL[subsetstring1]  # cut away transactions after test end date
        if (dim(OL)[1] > 0) {    # only if there are trades        
          if (flag == 1) {
            OLDF <- as.data.frame(OL)
            flag <- 0
          } else {
            OLDF <- rbind(OLDF, as.data.frame(OL))
          }
        }
      }
    }
    # perform blotter operations. create own portfolio/account for every symbol
    pstring <- paste(portfoliostring, symstring)
    astring <- paste(accountstring, symstring)
    # blotter environment for single symbol
    openBlotterEnvironment(pstring, astring, initDate=fromtodates[1], reset=FALSE, initEq=initEq)
    insertPositionIntoBlotter(pstring, symstring)
    insertTransactionsIntoBlotter(pstring, astring, symstring, OLDF, TxnSize=EqPerTrade, TxnFees=TxnFees)
    # blotter environment for group
    #if (count == 1) {
    #  gpstring <- paste(portfoliostring, paste(groupcode, "vadb", sep="."))
    #  gastring <- paste(accountstring, groupcode)
    #  openBlotterEnvironment(gpstring, gastring, initDate=portfStartDate, reset=FALSE, initEq=initEq*dim(groupinfo)[1])
    #}
    #count <- count + 1
    #insertPositionIntoBlotter(gpstring, symstring)
    #insertTransactionsIntoBlotter(gpstring, gastring, symstring, OLDF, TxnSize=EqPerTrade, TxnFees=TxnFees)    
  }
  return(OLDF)
}

# now that all blotter accounts and portfolio are saved, further inspection
# may be done with the function PerformanceSummary